<template>
<div class="page-container">
    <!-- 面包屑部分 -->
    <div class="breadcrumb">
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>营销中心</el-breadcrumb-item>
            <el-breadcrumb-item>优惠券</el-breadcrumb-item>
            <el-breadcrumb-item>优惠券活动列表</el-breadcrumb-item>
        </el-breadcrumb>
    </div>

    <!--工具栏-->
    <div class="toolbar">
        <el-form :inline="true" :model="filters" :size="size" ref="filters" :rules="filtersRules">
            <el-row class="times">
                <el-form-item label="活动时间：" prop="startTime">
                    <el-date-picker v-model="filters.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" placeholder="开始时间" class="input_postion" clearable @change="changeStartDate" :picker-options="startDateDisabled"></el-date-picker>
                </el-form-item>
                <span class="times-to">-</span>
                <el-form-item prop="endTime">
                    <el-date-picker v-model="filters.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" placeholder="结束时间" class="input_postion" clearable @change="changeEndDate" :picker-options="endDateDisabled"></el-date-picker>
                </el-form-item>  
                <el-form-item prop="creator" label="创建人：">
                    <el-input clearable v-model="filters.creator" placeholder="创建人" maxlength="80"></el-input>
                </el-form-item>     
            </el-row>
            <el-row class="search-input">
                <el-form-item prop="promName" label="活动名称：">
                    <el-input clearable v-model="filters.promName" placeholder="活动名称" maxlength="80"></el-input>
                </el-form-item>
                <el-form-item prop="promotionId" label="活动ID：">
                    <el-input clearable v-model="filters.promotionId" placeholder="活动ID"></el-input>
                </el-form-item>
                <el-form-item prop="endTime"></el-form-item>
            </el-row>

            <el-row class="search-button">
                <el-form-item>
                    <kt-button :label="$t('action.reset')" class="resetButton" icon="el-icon-refresh" @click="resetCouponForm()" />
                </el-form-item>
                <el-form-item>
                    <kt-button icon="el-icon-search" label="搜索" @click="getPromotionList()" class="searchButton" />
                </el-form-item>

                <el-form-item>
                  <!--perms="market:coupon:add"  ？？？？？-->
                    <kt-button label="创建活动" @click="createPage()" class="searchButton"  />
                </el-form-item>
            </el-row>
        </el-form>
    </div>
    <div class="tab-container">
        <el-tabs v-model="activeName">
            <el-tab-pane v-for="item in tabMapOptions" :key="item.key" :label="item.label" :name="item.key"></el-tab-pane>
            <!-- tab表格 -->
            <el-table :data="tableData" :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}" :highlight-current-row="true" :max-height="1500" :size="size" v-loading="loading" :align="align">
                <el-table-column align="center" prop="promotionId" label="活动ID" width="300"></el-table-column>
                <!-- <el-table-column align="center" prop="channelCodess" label="活动渠道" width="240"></el-table-column> -->
                <el-table-column align="center" prop="promName" label="优惠券名称" width="240"></el-table-column>
                <el-table-column align="center" label="优惠券范围" width="240">
                    <template slot-scope="scope">
                        <span v-if="scope.row.couponPlatform == 1">平台券</span>
                        <span v-else-if="scope.row.couponPlatform == 2">商户券</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="优惠券类型" width="240">
                    <template slot-scope="scope">
                        <span v-if="scope.row.couponType == 0">电子券</span>
                        <span v-else-if="scope.row.couponType == 1">实体券</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="金额抵扣类型" width="240">
                    <template slot-scope="scope">
                        <span v-if="scope.row.amountDeductType == 0">商品券</span>
                        <span v-else-if="scope.row.amountDeductType == 1">运费券</span>
                        <span v-else-if="scope.row.amountDeductType == 2">代金券</span>
                        <span v-else-if="scope.row.amountDeductType == 3">话费抵用券</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="使用条件" width="240">
                    <template slot-scope="scope">
                        满 {{scope.row.useTotalAmountLimit}} 元可用
                    </template>
                </el-table-column>
                <el-table-column align="center" label="优惠券面值" width="240">
                    <template slot-scope="scope">
                        {{scope.row.couponAmount}} 元
                    </template>
                </el-table-column>
                <el-table-column align="center" label="总限额(张)" width="240">
                    <template slot-scope="scope">
                        {{scope.row.idLimitNum == null || scope.row.idLimitNum == '' ? "无限制" : scope.row.idLimitNum}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="每人限领（张）" width="240">
                    <template slot-scope="scope">
                        {{scope.row.idLimitDayNum == null || scope.row.idLimitDayNum == '' ? "无限制" : scope.row.idLimitDayNum}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="开始时间/结束时间" width="360">
                    <template slot-scope="scope">
                        <span v-if="scope.row.startTime != null && scope.row.endTime != null">{{scope.row.startTime}}至{{scope.row.endTime}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="address" label="活动状态" width="100">
                    <template slot-scope="scope">
                        <span v-if="scope.row.status == 9">活动草稿</span>
                        <span v-else-if="statusFormat(scope.row) == 11">待提交</span>
                        <span v-else-if="statusFormat(scope.row) == 12">待审核</span>
                        <span v-else-if="statusFormat(scope.row) == 13">未开始</span>
                        <span v-else-if="statusFormat(scope.row) == 14">审核未通过</span>
                        <span v-else-if="statusFormat(scope.row) == 15">进行中</span>
                        <span v-else-if="statusFormat(scope.row) == 16">已过期</span>
                        <span v-else-if="statusFormat(scope.row) == 17">已结束</span>
                        <span v-else-if="scope.row.status == 7">已关闭</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="creatorName" label="创建人" width="240"></el-table-column>
                <el-table-column align="center" prop="createTime" label="创建时间" width="240"></el-table-column>
                <el-table-column align="left" fixed="right" label="操作" width="550 ">
                    <template slot-scope="scope">
                        <el-button @click="handleClick(scope.row)" v-if="scope.row.status != 9" type="text" size="mini" style>查看</el-button>
                        <kt-button type="text" size="mini" v-if="scope.row.status == 9 || statusFormat(scope.row) == 11 || statusFormat(scope.row) == 14" v-show="scope.row.editFlag" @click="editInfo(scope.row)" perms="market:coupon:edit" label="编辑" />
                        <kt-button type="text" size="mini" v-if="statusFormat(scope.row) == 11 || scope.row.status == 9" v-show="scope.row.editFlag" @click="deleteInfo(scope.row)" perms="market:coupon:delete" label="删除" />
                        <kt-button type="text" size="mini" v-if="scope.row.status != 9" @click="copyInfo(scope.row)" v-show="scope.row.editFlag" perms="market:coupon:copy" label="复制" />
                        <kt-button type="text" size="mini" v-if="statusFormat(scope.row) == 13 || statusFormat(scope.row) == 15" v-show="scope.row.editFlag" @click="closeInfo(scope.row)" perms="market:coupon:close" label="关闭" />
                        <kt-button type="text" size="mini" v-if="(statusFormat(scope.row) == 13 || statusFormat(scope.row) == 15) &&  checkTrigger(scope.row.triggerType)" v-show="scope.row.editFlag" @click="sendCouponInfo(scope.row)" perms="market:coupon:close" label="发放优惠券" />
                        <kt-button type="text" size="mini" v-if="(statusFormat(scope.row) == 13 || statusFormat(scope.row) == 15 || statusFormat(scope.row) == 17 || scope.row.status == 7) &&  checkTrigger(scope.row.triggerType)" v-show="scope.row.editFlag" @click="viewSendCouponlog(scope.row)" perms="market:coupon:close" label="发券记录" />
                    </template>
                </el-table-column>
            </el-table>
            <div class="t_r">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="filters.start" :page-sizes="[10, 20, 50, 100 ,300 , 500]" :page-size="filters.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
            </div>
        </el-tabs>
    </div>
    <backstageSendCoupon ref="backstageSendCoupon"></backstageSendCoupon>
</div>
</template>

<script>
import {
    front_prom_types,
    chanel_codes,
    prom_types
} from "@/market/dict/marketDict";
import KtButton from "@/views/Core/KtButton";
import {
    format
} from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import {
    darkmagenta
} from "color-name";
import tabPane from "./components/TabPaneSeckill";
import {
    channelCodeConverter
} from "@/market/dict/marketDict";

import backstageSendCoupon from "./components/backstageSendCoupon";

export default {
    name: "Tab",
    components: {
        tabPane,
        KtButton,
        TableColumnFilterDialog,
        backstageSendCoupon
    },
    data() {
        return {
            channelOption: [],
            templateDataFormRules: {
                //templateName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
            },
            filtersRules: {
                // promName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
                // creator: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
            },

            pageNumber: 1,
            pageSize: 10,
            total: 0,
            loading: false,
            align: "center",
            tableData: [],
            flag: false,
            form: {
                region: ""
            },
            option1: 1,
            option1: 2,
            option1: 3,
            tabMapOptions: [{
                    label: '全部',
                    key: '99'
                },
                {
                    label: '进行中',
                    key: '5'
                },
                {
                    label: '已结束',
                    key: '8'
                },
                {
                    label: '已过期',
                    key: '6'
                },
                {
                    label: '已关闭',
                    key: '7'
                },
                {
                    label: '未开始',
                    key: '3'
                },
                {
                    label: '待提交',
                    key: '1'
                },
                {
                    label: '待审核',
                    key: '2'
                },
                {
                    label: '审核未通过',
                    key: '4'
                },
                {
                    label: '活动草稿',
                    key: '9'
                },
            ],
            activeName: "99",
            createdTimes: 0,
            size: "small",
            filters: {
                promName: null,
                id: "",
                promType: 11,
                channelCode: "",
                activityType: "",
                merchantId: null,
                creator: "",
                startTime: "",
                endTime: "",
                operatorStoreId: null,
                type: "",
                status: null,
                t: "sysConfig",
                queryname: "",
                start: 1,
                limit: 10
            },
            frontPromTypes: this.getFrontPromType(),
            promTypes: this.getPromType(),
            channelCodes: chanel_codes,
            activityTypes: [{
                    activityType: "",
                    label: "请选择"
                },
                {
                    activityType: "0",
                    label: "自建"
                },
                {
                    activityType: "1",
                    label: "报名"
                }
            ],
            merchantIds: [{
                merchantId: null,
                label: "请选择"
            }],
            storeIds: [{
                storeId: null,
                label: "请选择"
            }],
            joinCheck: [],
            joinList: ["已使用用户", "未使用用户"],
            wayCheck: [],
            wayList: ["短信", "小程序", "网站", "H5", "邮件"],
            couponTemplatedialogVisible: false, //活动模板弹窗
            templateDataForm: {
                start: 1,
                limit: 10,
                promType: 11 //优惠券
            }, //模板搜索条件
            templateTableData: [], //模板List
            templateLoading: false, //模板table加载状态
            templateListTotal: 0, //模板LIst总条数
            tabsIndex: "first",

            startDateDisabled: {}, //开始时间限制
            endDateDisabled: {}, //结束时间限制

        };
    },
    methods: {
        changeStartDate: function () {
            var this_ = this;
            this_.endDateDisabled = {
                disabledDate: time => {
                    if (this_.filters.startTime) {
                        return time.getTime() <= new Date(this_.filters.startTime).getTime();
                    }
                }
            };
        },
        changeEndDate: function () {
            var this_ = this;
            this_.startDateDisabled = {
                disabledDate: time => {
                    if (this_.filters.endTime) {
                        return time.getTime() >= new Date(this_.filters.endTime).getTime();
                    }
                }
            };
        },

        viewSendCouponlog(row) {
            this.$refs.backstageSendCoupon.viewSendLog(row);
        },
        /**
         * 发放优惠券
         */
        sendCouponInfo(row) {
            // this.$message({"type":"success","message":"发送优惠券"})
            this.$refs.backstageSendCoupon.openDialog(row);
        },
        /**
         * 校验触发
         */
        checkTrigger(row) {
            return row.includes("40");
        },
        /**
         * 状态格式化
         */
        statusFormat(row) {
            if (
                row.status == 1 &&
                new Date().getTime() <= new Date(row.startTime).getTime()
            ) {
                //待提交
                return 11;
            } else if (
                row.status == 2 &&
                new Date().getTime() <= new Date(row.startTime).getTime()
            ) {
                //待审核
                return 12;
            } else if (
                row.status == 11 &&
                new Date().getTime() <= new Date(row.startTime).getTime()
            ) {
                //未开始
                return 13;
            } else if (
                row.status == 4 &&
                new Date().getTime() <= new Date(row.startTime).getTime()
            ) {
                //审核未通过
                return 14;
            } else if (
                row.status == 11 &&
                new Date().getTime() >= new Date(row.startTime).getTime() &&
                new Date().getTime() <= new Date(row.endTime).getTime()
            ) {
                //进行中
                return 15;
            } else if (
                (row.status == 1 || row.status == 2 || row.status == 4) &&
                new Date().getTime() > new Date(row.startTime).getTime()
            ) {
                //已过期
                return 16;
            } else if (
                row.status == 11 &&
                new Date().getTime() > new Date(row.endTime).getTime()
            ) {
                //已结束
                return 17;
            }
        },

        /**
         * 编辑
         */
        editInfo(row) {
            this.$router.push({
                path: "/CouponComponents/" + row.promotionId + "/1",
            });
        },
        details(row) {
            this.$router.push({
                path: "/CouponComponents/" + row.promotionId + "/1",
            });
        },
        /**
         * 删除
         */
        deleteInfo(row) {
            let that = this;
            this.$confirm("确定要执行删除操作么？删除后不可恢复!", "提示", {
                    type: "warning",
                    closeOnClickModal: false,
                })
                .then(() => {
                    this.utils.request.couponDeleteConfig({
                            promotionId: row.promotionId
                        },
                        res => {
                            that.$message({
                                message: "删除成功",
                                type: "success"
                            });
                            that.findPage();
                        }
                    );
                })
                .catch(() => {});
        },
        /**
         * 复制
         */
        copyInfo(row) {
            let that = this;
            this.$confirm("确定要复制该活动？", "提示", {
                    type: "warning",
                    closeOnClickModal: false,
                })
                .then(() => {
                    this.utils.request.couponCopyConfig({
                            promotionId: row.promotionId
                        },
                        res => {
                            that.$message({
                                message: "复制成功",
                                type: "success"
                            });
                            that.findPage();
                        }
                    );
                })
                .catch(() => {});
        },
        /**
         * 关闭
         */
        closeInfo(row) {
            let that = this;
            let flag = "正在进行中";
            if (row.status == 11 &&
                new Date().getTime() <= new Date(row.startTime).getTime()) {
                flag = "即将进行";
            }
            this.$confirm(
                    "该活动" + flag + "，确定要关闭它？关闭后不可再次开启。",
                    "提示", {
                        type: "warning",
                        closeOnClickModal: false,
                    }
                )
                .then(() => {
                    this.utils.request.couponCloseConfig({
                            promotionId: row.promotionId
                        },
                        res => {
                            that.$message({
                                message: "关闭成功",
                                type: "success"
                            });
                            that.findPage();
                        }
                    );
                })
                .catch(() => {});
        },
        handleClick(row) {
            this.$router.push({
                path: "/CouponDetail",
                query: {
                    promotionId: row.promotionId
                }
            });
        },
        handleSizeChange(val) {
            this.$set(this.filters, "limit", val);
            this.findPage();
        },
        handleCurrentChange(val) {
            this.$set(this.filters, "start", val);
            this.findPage();
        },
        findPage() {
            let that = this;
            this.loading = true;
            this.filters.merchantId =
                this.filters.merchantId == "" ? null : this.filters.merchantId;
            this.filters.operatorStoreId =
                this.filters.operatorStoreId == "" ?
                null :
                this.filters.operatorStoreId;

            this.filters.status =
                this.filters.status == "99" ? null : this.filters.status;
            this.utils.request.couponQueryConfigPage(this.filters, res => {
                that.loading = false;
                that.tableData = res.data.rows;
                that.total = res.data.total;
            });
        },
        // 时间格式化
        dateFormat: function (row, column, cellValue, index) {
            return format(row[column.property]);
        },
        resetCouponForm() {

            this.resetForm("filters");
            this.getPromotionList();
        },
        resetForm(formName) {
            if (this.$refs[formName] != undefined) {
                this.$refs[formName].resetFields();
            }
            this.$set(this.filters, "start", 1);
            this.$set(this.filters, "limit", 10);
            this.findPage();
        },
        createPage() {
            this.$router.push("/CouponComponents/0/1");
            // this.$router.push("/CreatePromotion"+"?auth=1");
        },
        getPromotionList() {
            // this.filters.start = 1;
            this.$set(this.filters, "start", 1);
            this.findPage();
            // this.$refs.child[0].listQuery.pageNo = 1;
            // this.$refs.child[0].getList();
        },
        getFrontPromType: function (row, column, cellValue, index) {
            return front_prom_types.filter(e => {
                return e.code == "skill_front_prom_type";
            });
        },

        getPromType: function (row, column, cellValue, index) {
            return prom_types.filter(e => {
                return e.code == "skill_promotion";
            });
        },
        checked() {
            this.flag = false;
            if (this.form.region == "one") {
                this.$router.push("/SeckillPromotionEvent" + "?auth=0");
            } else if (this.form.region == "two") {
                this.$router.push("/GroupActivityComponents?auth=0");
            } else {
                this.$router.push("/CreatePromotion3");
            }
        },
        SecondSell() {
            this.flag = true;
        },
    },
    watch: {
        activeName(val) {
            // this.$router.push(`${this.$route.path}?tab=${val}`);
            this.filters.status = val == "0" ? "" : val;
            this.$set(this.filters, "start", 1);
            this.$set(this.filters, "limit", 10);
            this.findPage();
        }
    },
    created() {
        const tab = this.$route.query.tab;
        if (tab) {
            this.activeName = tab;
        }
    },
    mounted() {
        //查询列表
        this.findPage();
    }
};
</script>

<style lang="scss" scoped>
/deep/ .el-tabs--card>.el-tabs__header .el-tabs__item:first-child {
    border-left: 1px solid #9B9DA3 !important;

    &.is-active {
        border-color: #0090FF !important;
    }
}
</style>
